<?php
namespace app\controller\model;

use app\BaseController;
class Pay extends BaseController
{
    public $mobile="";
    public function __construct($mobile='',$code='',$ctype=1){
        $this->mobile = $mobile ;
    }
    public function pay2($transaction_id='',$openID='',$amount=1){
        $out_trade_no = rand_md5();
        $url="https://api.mch.weixin.qq.com/secapi/pay/profitsharing";
        $order_arr = [
            'mch_id' =>  Config::wxConfig()['mchid'],
            'appid' =>  Config::wxConfig()['appid'],
            'nonce_str' =>  $out_trade_no,
            'transaction_id' =>  $transaction_id,
            'out_order_no' =>  $out_trade_no,
            'receivers' =>  json_encode([[
                'type'=>'PERSONAL_OPENID',
                'account'=>$openID,
                'amount'=>$amount,
                'description'=>'推广分账',
            ]],JSON_UNESCAPED_UNICODE)
        ];
        ksort($order_arr);
        $str='';
        foreach ($order_arr as $k=>$v){
            $str .= $k."=".$v."&";
        }
        $str=trim($str,"&")."&key=".Config::wxConfig()['secretpay'];
        $order_arr['sign']=strtoupper(bin2hex(hash_hmac('sha256',$str,Config::wxConfig()['secretpay'],true)));
        $xml=$this->arr_to_xml($order_arr);

        $re=post_xml($url,$xml,true);
        $arrays = simplexml_load_string($re);
        if(isset($arrays->order_id)){
            $reOrderID = (string)$arrays->order_id;
            //分账成功
            if(strlen($reOrderID)>10){
                return [1,$out_trade_no,(string)$arrays->order_id];
            }else{
                return [0,(string)$arrays->err_code,(string)$arrays->err_code_des];
            }
        }else{
            return [0,(string)$arrays->err_code,(string)$arrays->err_code_des];
        }
    }
    protected function arr_to_xml($data, $root = true)
    {
        $str = "";
        if ($root) {
            $str .= "<xml>";
        }
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $child = $this->arr_to_xml($val, false);
                $str .= "<$key>$child</$key>";
            } else {
                $str .= "<$key><![CDATA[$val]]></$key>";
            }
        }
        if ($root) {
            $str .= "</xml>";
        }
        return $str;
    }
}
?>